package com.usc.csci588.chaltrojan.ui.main;

import java.io.ByteArrayOutputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.location.Location;
import android.os.AsyncTask;
import android.util.Log;

import com.usc.csci588.chaltrojan.login.Constants;


public class SendLocationUpdate extends AsyncTask<String, Void, Void> {
	
	public String locationURL;
	public double lat;
	public double lng;
	Location myInitialLocation = null;
	
	
	public SendLocationUpdate(double lat, double lng) {
		// TODO Auto-generated constructor stub
		this.lat = lat;
		this.lng = lng;
	}
	
	public SendLocationUpdate()
	{
		lat = 34;
		lng = -118;
			
	}
	
	public String executeGetRequest(String getURL) {
		
		Log.d("updateLocation", "Going to execute:" + getURL);
		String responseStr = "";
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(getURL);
		try {
			HttpResponse response = httpClient.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity entity = response.getEntity();
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				entity.writeTo(out);
				out.close();
				responseStr = out.toString();
				// do something with response
				Log.d("updateLocation", responseStr);				
			} else {
				responseStr = "Could not connect.";
			}
		} catch (Exception ee) {
			// handle exception			
		} 

		Log.d("locationUpdate", responseStr);
		return responseStr;
	}
	
	
	public String constructLocationURL(String handle)
	{
		String locationurl = Constants.ChalTrojanHostName;
		locationurl += "/ChalTrojan2/UpdateLocation?lat="+lat+"&long="+lng+"&handle="+handle;
		
		return locationurl;
		
	}	
	

	@Override
	protected Void doInBackground(String... params) {
		// TODO Auto-generated method stub		
		String handle = params[0];
		if(handle.equals(null) || handle.equals(""))
		{
			handle = "default_user";
		}
		locationURL = constructLocationURL(handle);
		executeGetRequest(locationURL);		
		
		return null;		
		
	}
	
	
	@Override
	protected void onPostExecute(Void result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		Log.d("locationUpdate","Location updated successfully.");
		
	}

}
